package com.sairobo.admin.modules.wechat.servlet;

import com.sairobo.admin.modules.wechat.util.WechatUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 *作废-仅供测试
 */
//@WebServlet("/")
public class CallBackServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取微信回调请求中的code
        System.out.printf("in WxAuth/callBack");
        String code = req.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                    + "appid=" + WechatUtil.APPID
                    + "&secret=" + WechatUtil.APPSECRET
                    + "&code=" + code
                    + "&grant_type=authorization_code";
        //2. 向微信发出请求，带上APPSCECRET和code，获取openid和access_toekn
        JSONObject jsonObject = WechatUtil.doGetJson(url);
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");
        //4. 获取用户信息
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
                        + "access_token=" + token
                        + "&openid=" + openid
                        + "&lang=zh_CN";
        JSONObject userInfo = WechatUtil.doGetJson(infoUrl);
        System.out.println("登录成功~~~~~~~~~~~~~~~~"+userInfo);

        //1. 使用微信用户信息直接登录，无需注册和绑定



        req.setAttribute("info", userInfo);
        req.getRequestDispatcher("/index1.jsp").forward(req, resp);
    }
}
